package com.ruoyi.quartz.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.constant.CacheKeyConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component("huobiTask")
public class HuobiTask {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ISysConfigService sysConfigService;
    public void getExchangeRate() {
        String result = HttpUtils.sendGet("https://www.huobi.com/-/x/general/exchange_rate/list", "r=qh2i7n");
        if(StringUtils.isNotEmpty(result)) {
            JSONObject resultjo = JSON.parseObject(result);
            if(resultjo.getIntValue("code") == 200 && resultjo.getBooleanValue("success")) {
                JSONArray rateArray = resultjo.getJSONArray("data");
                if(rateArray != null && rateArray.size() > 0) {
                    for(int i = 0; i < rateArray.size(); i++) {
                        JSONObject ratejo = rateArray.getJSONObject(i);
                        String name = ratejo.getString("name");
                        BigDecimal rate = ratejo.getBigDecimal("rate");
                        redisTemplate.opsForHash().put(CacheKeyConstants.EXCHANGE_RATE, name, rate);
                        if(Constants.USDT_CNY.equals(name)) {
                            UpdateWrapper<SysConfig> updateWrapper = new UpdateWrapper<>();
                            updateWrapper.eq("config_key", Constants.USDT_CNY);
                            updateWrapper.set("config_value", rate);
                            sysConfigService.update(updateWrapper);
                        }
                    }
                }
            }
        }
    }
}
